package org.amphiprion.diceroller.util;

import java.util.Locale;

import org.amphiprion.diceroller.ApplicationConstants;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.util.Log;

public class PreferenceUtil {
	public static final String KEY_CODE_VERSION = "pref_code_version";

	public static final String KEY_PREF_LANGUAGE = "pref_language";
	public static final String KEY_PREF_PRODUCT_LIST = "pref_product_list";
	public static final String KEY_PREF_RESTORE_XML = "pref_restore_xml";
	public static final String KEY_PREF_LANGUAGE_CHOICE = "pref_language_list";

	private static SharedPreferences pref;
	public static Context context;

	public static void init(Context context) {
		PreferenceUtil.context = context;
		PreferenceUtil.pref = PreferenceManager.getDefaultSharedPreferences(context);

		PreferenceUtil.setLanguage(PreferenceUtil.getLanguage());
	}

	public static String getLanguage() {
		return pref.getString(KEY_PREF_LANGUAGE, Locale.getDefault().getLanguage());
	}

	public static void setLanguage(String lang) {
		Editor editor = pref.edit();
		editor.putString(KEY_PREF_LANGUAGE, lang);
		editor.commit();

		Locale locale2 = new Locale(lang);
		Locale.setDefault(locale2);
		Configuration config2 = new Configuration();
		config2.locale = locale2;
		context.getResources().updateConfiguration(config2, context.getResources().getDisplayMetrics());
	}

	public static boolean isFirstRunForThisVersion() {
		int savedCodeVersion = pref.getInt(KEY_CODE_VERSION, -1);
		PackageInfo pInfo;
		try {
			pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			int codeVersion = pInfo.versionCode;
			if (codeVersion != savedCodeVersion) {
				Editor editor = pref.edit();
				editor.putInt(KEY_CODE_VERSION, codeVersion);
				editor.commit();
				return true;
			} else {
				return false;
			}
		} catch (NameNotFoundException e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			return false;
		}
	}
}
